//
//  WBUserAccount.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/21.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit
//FIXME:用不用转成NSString有待验证
fileprivate let accountFile = "userAccount.json"

class WBUserAccount: NSObject {
    
    /// 访问令牌
    var access_token:String?
    
    /// 用户代号
    var uid:String?
    
    /// 过期日期
    var expires_in:TimeInterval = 0.0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expiresDate:Date?
    
    /// 用户昵称
    var screen_name:String?
    
    /// 用户头像大图
    var avatar_large:String?
    
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        //从磁盘加载保存的文件 得到一个字典
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent(accountFile)
        
        guard let data = NSData(contentsOfFile: jsonPath),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject] else {
            return
        }
        
        //使用字典设置属性值
        //用户登录的关键信息
        yy_modelSet(with: dict ?? [:])
        
        //判断token是否过期
        //测试过期日期
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)
        
        if expiresDate?.compare(Date()) != .orderedDescending {
//            print("账户过期")
            //清空token
            access_token = nil
            uid = nil
            
            //删除账户文件
             _ = try? FileManager.default.removeItem(atPath: jsonPath)
        }
        
//        print("账户正常\(self)")
        
    }
    
    /**
     1.偏好设置(小)
     2.沙盒-归档/plist/json
     3.数据库
     4.钥匙串(小/自动加密-需要使用框架 SSKeychain)
     
    */
    
    func saveAccount() {
        //1.模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String:AnyObject]) ?? [:]
        
        dict.removeValue(forKey: "expires_in")
        //2.字典序列化
        //FIXME:需要修改路径
       guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
        
        else{
            return
        }
        
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent(accountFile)
//        print(jsonPath)
        
//        let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask, true)
//        let documnetPath = documentPaths[0]
//        let str = "/useraccount.json"
        
//        let path = "\(documnetPath)/\(accountFile)"
        
        //3.写入磁盘
       (data as NSData).write(toFile: jsonPath, atomically: true)
        
        //保存模型
                
    }
}
